import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: HP
 * Date: 2023 -06 -10
 * Time: 16:36
 */
public class PriorityQueue {
    private int[] elem;
    private int usedSize;

    public PriorityQueue() {
        elem=new int[10];
        usedSize=0;
    }

    /**
     * 建堆的时间复杂度：O(n)
     *
     * @param array
     */
    public void createHeap(int[] array) {
        for (int parent = (array.length-1-1)/2; parent >= 0 ; parent--) {
            shiftDown(array,parent,array.length);
        }
    }
    public void heapSort(int[] arr){
        createHeap(arr);
        for(int i=arr.length-1;i>=0;i--){
            int t=arr[0];
            arr[0]= arr[i];
            arr[i]=t;
            shiftDown(arr,0,i);
        }
    }


    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int[] elem,int root,int len) {
        int child=root*2+1;
        while(child<len){
            if(child+1<len&&elem[child+1]>elem[child]){//大根堆，找大的比较
                child+=1;
            }
            if(elem[root]<elem[child]){
                int t=elem[root];
                elem[root]=elem[child];
                elem[child]=t;

                root=child;
                child=child*2+1;
            }else{
                break;
            }
        }
    }


    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()){
            elem= Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize]=val;
        usedSize++;
        shiftUp(usedSize-1);
    }

    private void shiftUp(int child) {
        int parent=(child-1)/2;
        while(child>0){
            if(elem[parent]<elem[child]){
                int t=elem[parent];
                elem[parent]=elem[child];
                elem[child]=t;

                child=parent;
                parent=(parent-1)/2;
            }else{
                break;
            }
        }
    }

    public boolean isFull() {
        return elem.length==usedSize;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void poll() {
        if(isEmpty()) throw new RuntimeException("优先级队列为空");
        int t=elem[0];
        elem[0]=elem[usedSize-1];
        elem[usedSize-1]=t;
        usedSize--;
        shiftDown(elem,0,usedSize);
    }

    public boolean isEmpty() {
        return usedSize==0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peek() {
        if(isEmpty()) throw new RuntimeException("优先级队列为空");
        return elem[0];
    }
    public static void main(String[] args) {
        PriorityQueue pq=new PriorityQueue();
        int []arr={1,8,4,5,6,2,9,4,3,0,1};
        pq.heapSort(arr);
        for (int e:arr) {
            System.out.print(e+" ");
        }
        System.out.println();
    }
}
